#!/usr/bin/env bash

include() {
  if [ ! -e "$1" ]
  then
    curl -skS "${CI_RUN:-http://mw-gitx.it}/shell/$1" > "$1"
    chmod +x "$1"
  fi
  # shellcheck disable=SC1090
  test "${2^^}" == "TRUE" && . "./$1"
  return 0
}

include ci-feishu.sh
include ci-vars.sh true

status=
case "${CI_JOB_STATUS}" in
  success)
    status=$(emoji "green heart")
    emoji_continue=$(emoji "hundred points")
    ;;
  failed)
    status=$(emoji "broken heart")
    emoji_continue=$(emoji "collision")
    ;;
  canceled)
    status=$(emoji "white heart")
    emoji_continue=$(emoji "prohibited")
    ;;
  *)
    status=$(emoji "yellow heart")
    emoji_continue=$(emoji "woman firefighter")
    ;;
esac

info=$(curl -H "PRIVATE-TOKEN:${PRIVATE_TOKEN}" -skS "${GITLAB_SERVER}/projects/${CI_PROJECT_ID}/pipelines/${CI_PIPELINE_ID}")
started_at=$(echo "${info}"|grep -Eo '"started_at":"[^"]+"'|awk -F\" '{print $4}')
#updated_at=$(echo "${info}"|grep -Eo '"updated_at":"[^"]+"'|awk -F\" '{print $4}')

((elapse=$(date +%s)-$(date -d "$(echo "${started_at}"|cut -c 1-19|tr 'T' ' ')" +%s)))
((elapse=$elapse+28800))

extra=""

if test -n "${triggered:-}"
then
  _e=$(emoji "bow and arrow")
  IFS=' ' read -r -a parts <<<"${triggered}"
  for part in "${parts[@]}"
  do
    extra+="\r\n${_e} ${part}"
  done
else
  extra+=""
fi

if test -n "${images:-}"
then
  IFS=';' read -r -a parts <<<"${images:1}"
  for part in "${parts[@]}"
  do
    extra+="\r\n${part}"
  done
else
  extra+=""
fi

if test -n "${redeployed:-}"
then
  IFS=';' read -r -a parts <<<"${redeployed:1}"
  for part in "${parts[@]}"
  do
    extra+="\r\n${part}"
  done
else
  extra+=""
fi

if test -n "${errors:-}"
then
  IFS=';' read -r -a parts <<<"${errors:1}"
  for part in "${parts[@]}"
  do
    extra+="\r\n${part}"
  done
else
  extra+=""
fi

text="${status} ${CI_PROJECT_NAMESPACE}/${CI_PROJECT_NAME}@${CI_BUILD_REF_NAME}(${elapse} seconds)\r\n${emoji_continue} ${CI_PROJECT_URL}/-/commit/${CI_COMMIT_SHA}(${CI_COMMIT_AUTHOR}): ${CI_COMMIT_TITLE//\"/\\\"}\r\n${emoji_continue} ${CI_PROJECT_URL}/-/pipelines/${CI_PIPELINE_ID}${extra}"

text="${text}" ./ci-feishu.sh "${@}"
